'use client';

import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { DashboardLayout } from '@/components/layout/dashboard-layout';
import { AdminGuard } from '@/components/auth/PermissionGuard';
import { formatAddress, formatDate, formatCurrency } from '@/lib/utils';
import { multiChainApi } from '@/lib/multi-chain-api';
import { useChain } from '@/context/ChainContext';
import { Search, Users, TrendingUp, Award, Gift, Eye } from 'lucide-react';

interface Referral {
  id: string;
  referrer_address: string;
  referred_address: string;
  referral_code: string;
  referral_level: number;
  total_rewards_earned: number;
  is_active: boolean;
  created_at: string;
}

interface POPReward {
  id: string;
  recipient_address: string;
  recipient_pop_level: string;
  source_address: string;
  source_pos_amount: number;
  generation: number;
  generation_percentage: number;
  reward_amount: number;
  settlement_date: string;
  is_distributed: boolean;
}

interface ReferralStats {
  total_referrals: number;
  active_referrals: number;
  total_pop_rewards: number;
  pending_rewards: number;
  avg_referral_depth: number;
  top_referrers_count: number;
}

interface ReferralTree {
  address: string;
  referral_code: string;
  level: number;
  direct_referrals: number;
  total_referrals: number;
  total_rewards: number;
  children: ReferralTree[];
}

export default function ReferralsPage() {
  const { currentChain } = useChain();
  const [searchTerm, setSearchTerm] = useState('');
  const [levelFilter, setLevelFilter] = useState<string>('all');
  const [selectedReferrer, setSelectedReferrer] = useState<string | null>(null);
  const [showTree, setShowTree] = useState(false);

  // Fetch referral stats
  const { data: stats } = useQuery<ReferralStats>({
    queryKey: ['referral-stats', currentChain],
    queryFn: async () => {
      const client = multiChainApi.getClient(currentChain);
      const response = await client.get('/api/v1/admin/referrals/stats');
      return response.data;
    },
    refetchInterval: 30000,
  });

  // Fetch referrals list
  const { data: referrals, isLoading } = useQuery<Referral[]>({
    queryKey: ['referrals', currentChain, searchTerm, levelFilter],
    queryFn: async () => {
      const params = new URLSearchParams();
      if (searchTerm) params.append('search', searchTerm);
      if (levelFilter !== 'all') params.append('level', levelFilter);
      
      const client = multiChainApi.getClient(currentChain);
      const response = await client.get(`/api/v1/admin/referrals/all?${params}`);
      return response.data;
    },
    refetchInterval: 30000,
  });

  // Fetch POP rewards
  const { data: popRewards } = useQuery<POPReward[]>({
    queryKey: ['pop-rewards', currentChain],
    queryFn: async () => {
      const client = multiChainApi.getClient(currentChain);
      const response = await client.get('/api/v1/admin/referrals/rewards');
      return response.data;
    },
    refetchInterval: 30000,
  });

  // Fetch referral tree for selected user
  const { data: referralTree } = useQuery<ReferralTree>({
    queryKey: ['referral-tree', currentChain, selectedReferrer],
    queryFn: async () => {
      if (!selectedReferrer) return null;
      const client = multiChainApi.getClient(currentChain);
      const response = await client.get(`/api/v1/admin/referrals/tree/${selectedReferrer}`);
      return response.data;
    },
    enabled: !!selectedReferrer,
  });

  const filteredReferrals = referrals?.filter(referral => {
    const matchesSearch = !searchTerm || 
      referral.referrer_address.toLowerCase().includes(searchTerm.toLowerCase()) ||
      referral.referred_address.toLowerCase().includes(searchTerm.toLowerCase()) ||
      referral.referral_code.toLowerCase().includes(searchTerm.toLowerCase());
    
    const matchesLevel = levelFilter === 'all' || referral.referral_level.toString() === levelFilter;
    
    return matchesSearch && matchesLevel;
  }) || [];

  const ReferralTreeNode = ({ node, depth = 0 }: { node: ReferralTree; depth?: number }) => (
    <div className={`${depth > 0 ? 'ml-6 border-l-2 border-gray-200 pl-4' : ''}`}>
      <div className="bg-white border rounded-lg p-4 mb-2 shadow-sm">
        <div className="flex items-center justify-between">
          <div>
            <div className="font-mono text-sm">{formatAddress(node.address)}</div>
            <div className="text-xs text-muted-foreground">
              Code: {node.referral_code} | Level: {node.level}
            </div>
          </div>
          <div className="text-right text-sm">
            <div>Direct: {node.direct_referrals}</div>
            <div>Total: {node.total_referrals}</div>
            <div className="font-medium">{formatCurrency(node.total_rewards)}</div>
          </div>
        </div>
      </div>
      {node.children && node.children.map((child, index) => (
        <ReferralTreeNode key={index} node={child} depth={depth + 1} />
      ))}
    </div>
  );

  return (
    <DashboardLayout>
      <AdminGuard>
        <div className="space-y-6">
        {/* Header */}
        <div>
          <h1 className="text-3xl font-bold tracking-tight">Referral Management</h1>
          <p className="text-muted-foreground">
            Monitor referral system and POP reward distribution
          </p>
        </div>

        {/* Stats Cards */}
        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-6">
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Total Referrals</CardTitle>
              <Users className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{stats?.total_referrals || 0}</div>
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Active Referrals</CardTitle>
              <TrendingUp className="h-4 w-4 text-green-600" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold text-green-600">{stats?.active_referrals || 0}</div>
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">POP Rewards</CardTitle>
              <Award className="h-4 w-4 text-purple-600" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{formatCurrency(stats?.total_pop_rewards || 0)}</div>
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Pending Rewards</CardTitle>
              <Gift className="h-4 w-4 text-orange-600" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold text-orange-600">{formatCurrency(stats?.pending_rewards || 0)}</div>
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Avg Depth</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{stats?.avg_referral_depth?.toFixed(1) || 0}</div>
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Top Referrers</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{stats?.top_referrers_count || 0}</div>
            </CardContent>
          </Card>
        </div>

        {/* Tab Navigation */}
        <div className="flex space-x-1 bg-muted p-1 rounded-lg w-fit">
          <Button
            variant={!showTree ? "primary" : "ghost"}
            size="sm"
            onClick={() => setShowTree(false)}
          >
            Referrals List
          </Button>
          <Button
            variant={showTree ? "primary" : "ghost"}
            size="sm"
            onClick={() => setShowTree(true)}
          >
            POP Rewards
          </Button>
        </div>

        {!showTree ? (
          // Referrals List
          <Card>
            <CardHeader>
              <CardTitle>Referrals List</CardTitle>
              <CardDescription>All referral relationships and their performance</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="flex flex-col sm:flex-row gap-4 mb-6">
                <div className="flex-1 relative">
                  <Search className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
                  <input
                    type="text"
                    placeholder="Search by address or referral code..."
                    className="w-full pl-10 pr-4 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                  />
                </div>
                <select
                  className="px-4 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  value={levelFilter}
                  onChange={(e) => setLevelFilter(e.target.value)}
                >
                  <option value="all">All Levels</option>
                  <option value="1">Level 1</option>
                  <option value="2">Level 2</option>
                  <option value="3">Level 3</option>
                  <option value="4">Level 4</option>
                  <option value="5">Level 5</option>
                </select>
              </div>

              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead>
                    <tr className="border-b">
                      <th className="text-left p-4">Referrer</th>
                      <th className="text-left p-4">Referred User</th>
                      <th className="text-left p-4">Referral Code</th>
                      <th className="text-left p-4">Level</th>
                      <th className="text-left p-4">Total Rewards</th>
                      <th className="text-left p-4">Status</th>
                      <th className="text-left p-4">Created</th>
                      <th className="text-left p-4">Actions</th>
                    </tr>
                  </thead>
                  <tbody>
                    {isLoading ? (
                      <tr>
                        <td colSpan={8} className="text-center p-8">
                          Loading referrals...
                        </td>
                      </tr>
                    ) : filteredReferrals.length === 0 ? (
                      <tr>
                        <td colSpan={8} className="text-center p-8 text-muted-foreground">
                          No referrals found
                        </td>
                      </tr>
                    ) : (
                      filteredReferrals.map((referral) => (
                        <tr key={referral.id} className="border-b hover:bg-muted/50">
                          <td className="p-4">
                            <div className="font-mono text-sm">
                              {formatAddress(referral.referrer_address)}
                            </div>
                          </td>
                          <td className="p-4">
                            <div className="font-mono text-sm">
                              {formatAddress(referral.referred_address)}
                            </div>
                          </td>
                          <td className="p-4">
                            <span className="bg-blue-100 text-blue-800 px-2 py-1 rounded text-sm">
                              {referral.referral_code}
                            </span>
                          </td>
                          <td className="p-4">
                            <span className={`px-2 py-1 rounded text-sm ${
                              referral.referral_level <= 2 ? 'bg-green-100 text-green-800' :
                              referral.referral_level <= 4 ? 'bg-yellow-100 text-yellow-800' :
                              'bg-red-100 text-red-800'
                            }`}>
                              Level {referral.referral_level}
                            </span>
                          </td>
                          <td className="p-4 font-medium">
                            {formatCurrency(referral.total_rewards_earned)}
                          </td>
                          <td className="p-4">
                            {referral.is_active ? (
                              <span className="bg-green-100 text-green-800 px-2 py-1 rounded text-sm">
                                Active
                              </span>
                            ) : (
                              <span className="bg-gray-100 text-gray-800 px-2 py-1 rounded text-sm">
                                Inactive
                              </span>
                            )}
                          </td>
                          <td className="p-4 text-sm text-muted-foreground">
                            {formatDate(referral.created_at)}
                          </td>
                          <td className="p-4">
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={() => setSelectedReferrer(referral.referrer_address)}
                            >
                              <Eye className="h-3 w-3 mr-1" />
                              Tree
                            </Button>
                          </td>
                        </tr>
                      ))
                    )}
                  </tbody>
                </table>
              </div>
            </CardContent>
          </Card>
        ) : (
          // POP Rewards
          <Card>
            <CardHeader>
              <CardTitle>POP Rewards</CardTitle>
              <CardDescription>Proof of Partnership reward distributions</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead>
                    <tr className="border-b">
                      <th className="text-left p-4">Recipient</th>
                      <th className="text-left p-4">POP Level</th>
                      <th className="text-left p-4">Source</th>
                      <th className="text-left p-4">Generation</th>
                      <th className="text-left p-4">Percentage</th>
                      <th className="text-left p-4">Reward Amount</th>
                      <th className="text-left p-4">Settlement Date</th>
                      <th className="text-left p-4">Status</th>
                    </tr>
                  </thead>
                  <tbody>
                    {popRewards && popRewards.length > 0 ? (
                      popRewards.map((reward) => (
                        <tr key={reward.id} className="border-b hover:bg-muted/50">
                          <td className="p-4">
                            <div className="font-mono text-sm">
                              {formatAddress(reward.recipient_address)}
                            </div>
                          </td>
                          <td className="p-4">
                            <span className={`px-2 py-1 rounded text-sm ${
                              reward.recipient_pop_level === 'TS' ? 'bg-purple-100 text-purple-800' :
                              reward.recipient_pop_level.startsWith('T') ? 'bg-green-100 text-green-800' :
                              'bg-gray-100 text-gray-800'
                            }`}>
                              {reward.recipient_pop_level}
                            </span>
                          </td>
                          <td className="p-4">
                            <div className="font-mono text-sm">
                              {formatAddress(reward.source_address)}
                            </div>
                            <div className="text-xs text-muted-foreground">
                              {formatCurrency(reward.source_pos_amount)} staked
                            </div>
                          </td>
                          <td className="p-4">
                            <span className={`px-2 py-1 rounded text-sm ${
                              reward.generation === 1 ? 'bg-green-100 text-green-800' :
                              reward.generation === 2 ? 'bg-blue-100 text-blue-800' :
                              reward.generation === 3 ? 'bg-yellow-100 text-yellow-800' :
                              'bg-gray-100 text-gray-800'
                            }`}>
                              Gen {reward.generation}
                            </span>
                          </td>
                          <td className="p-4">{reward.generation_percentage}%</td>
                          <td className="p-4 font-medium">
                            {formatCurrency(reward.reward_amount)}
                          </td>
                          <td className="p-4 text-sm">
                            {formatDate(reward.settlement_date)}
                          </td>
                          <td className="p-4">
                            {reward.is_distributed ? (
                              <span className="bg-green-100 text-green-800 px-2 py-1 rounded text-sm">
                                Distributed
                              </span>
                            ) : (
                              <span className="bg-orange-100 text-orange-800 px-2 py-1 rounded text-sm">
                                Pending
                              </span>
                            )}
                          </td>
                        </tr>
                      ))
                    ) : (
                      <tr>
                        <td colSpan={8} className="text-center p-8 text-muted-foreground">
                          No POP rewards found
                        </td>
                      </tr>
                    )}
                  </tbody>
                </table>
              </div>
            </CardContent>
          </Card>
        )}

        {/* Referral Tree Modal */}
        {selectedReferrer && referralTree && (
          <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
            <Card className="w-full max-w-4xl max-h-[80vh] overflow-y-auto">
              <CardHeader>
                <CardTitle>Referral Tree</CardTitle>
                <CardDescription>
                  {formatAddress(selectedReferrer)} - Referral network visualization
                </CardDescription>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  <ReferralTreeNode node={referralTree} />
                </div>
                <div className="flex justify-end gap-2 pt-4">
                  <Button variant="outline" onClick={() => setSelectedReferrer(null)}>
                    Close
                  </Button>
                </div>
              </CardContent>
            </Card>
          </div>
        )}
        </div>
      </AdminGuard>
    </DashboardLayout>
  );
}